<!-- 客户 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 用户列表 -->
      <el-col :lg="24" :xs="24">
        <curd-search
          :searchConfig="searchConfig"
          @query-click="queryClick"
          @reset-click="resetClick"
        />

        <!-- 列表 -->
        <!-- <curd-content
          ref="contentRef"
          :content-config="contentConfig"
          @add-click="handleAddClick"
          @edit-click="handleEditClick"
          @export-click="handleExportClick"
          @search-click="handleSearchClick"
          @toolbar-click="handleToolbarClick"
          @operat-click="handleOperatClick"
          @filter-change="handleFilterChange"
        /> -->

        <!-- <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex-x-between">
              <div>
                <el-button
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                >
                  <i-ep-delete />
                  批量删除
                </el-button>
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              label="客户名称"
              align="center"
              prop="clientWxName"
              width="180"
            />

            <el-table-column
              label="客户头像"
              align="center"
              prop="clientWxAvatar"
              width="140"
            >
              <template #default="scope">
                <el-avatar
                  :size="50"
                  :src="
                    scope.row.clientWxAvatar
                      ? `https://lsx.tianjinmaichong.com/api/${scope.row.clientWxAvatar}`
                      : '@/assets/images/default-avatar.png'
                  "
                />
              </template>
            </el-table-column>

            <el-table-column label="手机号码" align="center" width="140">
              <template #default="scope">
                <div v-if="scope.row.isPhone">
                  {{ judgePhone(scope.row.clientPhone.toString()) }}
                  <Hide
                    style="width: 1em; height: 1em; margin-left: 8px"
                    @click="scope.row.isPhone = !scope.row.isPhone"
                  />
                </div>
                <div v-else>
                  {{ scope.row.clientPhone }}
                  <View
                    style="width: 1em; height: 1em; margin-left: 8px"
                    @click="scope.row.isPhone = !scope.row.isPhone"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="关联律师"
              width="200"
              align="center"
              prop="lawyerName"
            />
            <el-table-column
              label="关联律所"
              width="200"
              align="center"
              prop="lawFirmName"
            />

            <el-table-column label="创建时间" align="center">
              <template #default="scope">
                <text>
                  {{
                    new Date(scope.row.createdAt)
                      .toISOString()
                      .replace("T", " ")
                      .substring(0, 19)
                  }}
                </text>
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="160">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="handleOpenDialog(scope.row)"
                >
                  <i-ep-edit />
                  关联律师
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.current"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card> -->
      </el-col>
    </el-row>

    <!-- 用户表单弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      title="关联律师"
      append-to-body
      @close="handleCloseDialog"
      size="34%"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="关联律师" prop="lawyerName">
          <div @click="isLawSelect = !isLawSelect">
            {{ formData.lawyerName }}
            <el-icon>
              <ArrowDown />
            </el-icon>
          </div>
        </el-form-item>

        <el-form-item label="律所名称" prop="lawFirmName">
          <div>
            {{ formData.lawFirmName }}
          </div>
        </el-form-item>
      </el-form>
      <LawyerSelect v-if="isLawSelect" @select-lawed="selectLaw" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Customers",
  inheritAttrs: false,
});
import clientAPI, {
  ClientPageQuery,
  ClientForm,
  ClientPageVO,
} from "@/api/client";
import { judgePhone } from "@/utils/helper";
import searchConfig from "./config/search";
import contentConfig from "./config/content";

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const pageData = ref<ClientPageVO[]>();

const isLawSelect = ref(false);

/** 用户查询参数  */
const queryParams = reactive<ClientPageQuery>({
  current: 1,
  pageSize: 10,
  cityNo: "",
  lawFirmId: undefined,
  lawyerId: undefined,
  clientName: "",
});

const queryClick = (item: any) => {
  console.log(item, "查询");
};
const resetClick = (item: any) => {
  console.log(item, "重置查询");
};
/**  用户弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});

// 用户表单数据
const formData = reactive<ClientForm>({
  lawyerId: undefined,
  lawyerName: "",
  lawFirmId: undefined,
  lawFirmName: "",
  id: undefined,
  caseId: null,
  clientCityName: "",
  clientCityNo: "",
  clientIp: "",
  clientName: "",
  clientPhone: "",
  clientWxAvatar: null,
  clientWxName: "",
  createdAt: "",
  email: null,
  gender: "",
  openid: null,
  updateAt: "",
  userType: "",
});

/** 用户表单校验规则  */
const rules = reactive({
  lawyerName: [
    { required: true, message: "律师名称不能为空", trigger: "blur" },
  ],
  lawFirmName: [
    { required: true, message: "律所名称不能为空", trigger: "blur" },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  clientAPI
    .getclientPage(queryParams)
    .then((data) => {
      console.log(data, "客户列表");
      let newList = data.records.map((item: any) => ({
        ...item,
        isPhone: true,
      }));
      pageData.value = newList;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(val?: any) {
  // console.log(val, "valval");
  dialog.visible = true;
  if (val) {
    dialog.title = "修改用户";
    // clientAPI.getFormData(id).then((data) => {
    //   Object.assign(formData, { ...data });
    // });
    Object.assign(formData, { ...val });
  } else {
    dialog.title = "新增用户";
  }
}
const selectLaw = (val: any) => {
  // console.log(val, "val");
  formData.lawFirmId = val.lawFirmId;
  formData.lawFirmName = val.lawFirmName;
  formData.lawyerId = val.id;
  formData.lawyerName = val.lawyerName;
};
/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = undefined;
  formData.lawyerId = undefined;
  formData.lawFirmId = undefined;
  isLawSelect.value = false;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.lawyerId;
      loading.value = true;
      clientAPI
        .clientBindLawyer(formData)
        .then(() => {
          if (userId) {
            ElMessage.success("关联律师成功");
          } else {
            ElMessage.success("新增用户成功");
          }
          handleCloseDialog();
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      clientAPI
        .deleteClientBatch(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
